package serverGUI;

import java.io.IOException;
import java.io.PipedInputStream;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

class ReaderThread extends Thread { 
	PipedInputStream pi;
	JTextArea consoleTextArea; 
	
	ReaderThread(PipedInputStream pi, JTextArea consoleTextArea) { 
		this.pi = pi; 
		this.consoleTextArea = consoleTextArea;
	} 
	
	public void run() { 
		final byte[] buf = new byte[1024]; 
		try { 
			while (true) { 
				final int len = pi.read(buf); 
				if (len == -1) { 
					break; 
				} 
				SwingUtilities.invokeLater(new Runnable() { 
					public void run() { 
						consoleTextArea.append(new String(buf, 0, len));

						// Make sure the last line is always visible
						consoleTextArea.setCaretPosition(consoleTextArea.getDocument().getLength()); 
					
						// Keep the text area down to a certain character size 
						int idealSize = 1000; 
						int maxExcess = 500; 
						int excess = consoleTextArea.getDocument().getLength() - idealSize; 
						if (excess >= maxExcess) { 
							consoleTextArea.replaceRange("", 0, excess); 
							//consoleTextArea.setCaretPosition(consoleTextArea.getDocument().getLength());
						} 
					} 
				}); 
			} 
		} catch (IOException e) { 
		} 
	}
}
